package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IJingfeiDeptService;
import com.ruoyi.system.service.IJingfeiDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 经费管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-04-10
 */
@Service
public class JingfeiDeptServiceImpl implements IJingfeiDeptService 
{
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private DeptZhuanjiaMapper deptZhuanjiaMapper;

    @Autowired
    private DeptidOlddeptidServiceImpl deptidOlddeptidService;

    @Autowired
    private ZhuanjiaBiandongDetailMapper zhuanjiaBiandongDetailMapper;
    @Autowired
    private ZhuanjiaMapper zhuanjiaMapper;

    @Autowired
    private JingfeiPiciMapper jingfeiPiciMapper;

    @Autowired
    private JingfeiDeptMapper jingfeiDeptMapper;

    @Autowired
    private JingfeiYueMapper jingfeiYueMapper;

    @Autowired
    private JingfeiDetailMapper jingfeiDetailMapper;

    @Autowired
    private IJingfeiDetailService jingfeiDetailService;

    private final List<String> tingfazhuangtaiList = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8");

    /**
     * 查询经费管理
     * 
     * @param id 经费管理主键
     * @return 经费管理
     */
    @Override
    public JingfeiDept selectJingfeiDeptById(String id)
    {
        return jingfeiDeptMapper.selectJingfeiDeptById(id);
    }

    /**
     * 查询经费管理列表
     * 
     * @param jingfeiDept 经费管理
     * @return 经费管理
     */
    @Override
    public List<JingfeiDept> selectJingfeiDeptList(JingfeiDept jingfeiDept)
    {
        return jingfeiDeptMapper.selectJingfeiDeptList(jingfeiDept);
    }

    /**
     * 新增经费管理
     * 
     * @param jingfeiDept 经费管理
     * @return 结果
     */
    @Override
    public int insertJingfeiDept(JingfeiDept jingfeiDept)
    {
        return jingfeiDeptMapper.insertJingfeiDept(jingfeiDept);
    }

    /**
     * 修改经费管理
     * 
     * @param jingfeiDept 经费管理
     * @return 结果
     */
    @Override
    public int updateJingfeiDept(JingfeiDept jingfeiDept)
    {
        return jingfeiDeptMapper.updateJingfeiDept(jingfeiDept);
    }

    /**
     * 批量删除经费管理
     * 
     * @param ids 需要删除的经费管理主键
     * @return 结果
     */
    @Override
    public int deleteJingfeiDeptByIds(String ids)
    {
        return jingfeiDeptMapper.deleteJingfeiDeptByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除经费管理信息
     * 
     * @param id 经费管理主键
     * @return 结果
     */
    @Override
    public int deleteJingfeiDeptById(String id)
    {
        return jingfeiDeptMapper.deleteJingfeiDeptById(id);
    }

    /**
     * 查询单位的批次
     *
     * @param deptId        单位ID
     * @param picimingcheng 批次名称
     */
    @Override
    public List<Map<String, Object>> selectDeptPiciByDeptid(String deptId, String picimingcheng) {
        return jingfeiDeptMapper.selectDeptPiciByDeptid(deptId, picimingcheng);
    }

    /**
     * 查询发放列表
     * @param jingfeipiciId 经费批次ID
     * @param deptId 单位ID
     */
    @Override
    public Map<String, List<Map<String, String>>> selectFafangList(String jingfeipiciId, String deptId) {

        ZoneId zoneId = ZoneId.systemDefault();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

        Dept parentDept = new Dept();
        parentDept.setParentid(deptidOlddeptidService.DeptIdToOldDeptId(deptId));
        Map<String, List<Map<String, String>>> fafanglist = new HashMap<>();
        List<Map<String, String>> deptList = new ArrayList<>();


        JingfeiPici jingfeiPici = jingfeiPiciMapper.selectJingfeiPiciById(jingfeipiciId);//经费批次

        LocalDateTime jisuanshijian = jingfeiPici.getJisuanshijian().toInstant().atZone(zoneId).toLocalDateTime();
        LocalDateTime kaishishijian = jingfeiPici.getKaishinianyue().toInstant().atZone(zoneId).toLocalDateTime();
        LocalDateTime jieshushijian = jingfeiPici.getJieshunianyue().toInstant().atZone(zoneId).toLocalDateTime();

        String jiezhiTime;//查找单位专家变动的截至时间
        if (jisuanshijian.isBefore(jieshushijian))
            jiezhiTime = jisuanshijian.format(dateTimeFormatter);
        else
            jiezhiTime = jieshushijian.format(dateTimeFormatter);

        List<Dept> childDeptList = deptMapper.selectDeptList(parentDept);
        for (Dept dept : childDeptList) {
            Dept childDept = new Dept();
            childDept.setParentid(dept.getId());
            List<Dept> childDepts = deptMapper.selectDeptList(childDept);
            List<ZhuanjiaBiandongDetail> deptZhuanjiaBiandongDetailList = zhuanjiaBiandongDetailMapper
                    .selectZhuanjiaBiandongDetailListByZhuanjiaIdAndDeptIdAndUsedAndTongguoOrJieshuTime(null,
                            deptidOlddeptidService.OldDeptIdToDeptId(dept.getId()), "0", "1",
                            jiezhiTime, jieshushijian.format(dateTimeFormatter));//查询单位是否提交专家变动
//            int notFafangCount1 = jingfeiDeptMapper.selectNotFafangCountByDeptId(deptidOlddeptidService.OldDeptIdToDeptId(dept.getId()));
            Map<String, String> deptIdNameIsFaYiFaMap = new HashMap<>();
            deptIdNameIsFaYiFaMap.put("deptId", deptidOlddeptidService.OldDeptIdToDeptId(dept.getId()));
            deptIdNameIsFaYiFaMap.put("deptName", dept.getJigoumingcheng());
            if (childDepts.size() > 0 || (deptZhuanjiaBiandongDetailList != null && deptZhuanjiaBiandongDetailList.size() != 0))
                deptIdNameIsFaYiFaMap.put("isFa", "1");
            else
                deptIdNameIsFaYiFaMap.put("isFa", "0");
            if (jingfeiDeptMapper.selectJingfeiDeptByJingfeipiciIdAndDeptId(jingfeipiciId,
                    deptidOlddeptidService.OldDeptIdToDeptId(dept.getId())).getIsfafang() == 1)
                deptIdNameIsFaYiFaMap.put("yiFa", "1");
            else
                deptIdNameIsFaYiFaMap.put("yiFa", "0");
            deptList.add(deptIdNameIsFaYiFaMap);
        }
        fafanglist.put("deptList", deptList);
        List<Zhuanjia> childZhuanjiaList = zhuanjiaMapper.selectZhuanjiaByDeptID(
                deptidOlddeptidService.DeptIdToOldDeptId(deptId), deptId);
        List<Map<String, String>> zhuanjiaList = new ArrayList<>();
        List<ZhuanjiaBiandongDetail> deptZhuanjiaBiandongDetailList = zhuanjiaBiandongDetailMapper
                .selectZhuanjiaBiandongDetailListByZhuanjiaIdAndDeptIdAndUsedAndTongguoOrJieshuTime(null,
                        deptId, "0", "1",
                        jiezhiTime, jieshushijian.format(dateTimeFormatter));//查询单位是否提交专家变动
        for (Zhuanjia zhuanjia : childZhuanjiaList) {
            String zhuanjiaId = zhuanjia.getZhuanjiaid();
            Map<String, String> zhuanjiaIdNameYiFaMap = new HashMap<>();
            zhuanjiaIdNameYiFaMap.put("zhuanjiaId", zhuanjiaId);
            zhuanjiaIdNameYiFaMap.put("zhuanjiaName", zhuanjia.getXingming());
            if (deptZhuanjiaBiandongDetailList == null || deptZhuanjiaBiandongDetailList.size() == 0)
                zhuanjiaIdNameYiFaMap.put("isFa", "0");
            else
                zhuanjiaIdNameYiFaMap.put("isFa", "1");
            JingfeiDetail jingfeiDetail = jingfeiDetailMapper.
                    selectAllByZhuangjiaidAndJingfeipiciid(zhuanjiaId, jingfeipiciId);
            if (jingfeiDetail == null)
                zhuanjiaIdNameYiFaMap.put("yiFa", "0");
            else
                zhuanjiaIdNameYiFaMap.put("yiFa", jingfeiDetail.getIsshoudao().toString());
            zhuanjiaList.add(zhuanjiaIdNameYiFaMap);
        }
        fafanglist.put("zhuanjiaList", zhuanjiaList);
        return fafanglist;
    }

    /**
     * 发放
     *
     * @param jingfeipiciId 经费批次ID
     * @param deptIds        单位ID
     * @return
     */
    @Override
    @Transactional
    public int updateIsfafangByJingfeipiciidAndDeptid(String jingfeipiciId, String[] deptIds, String[] zhuanjiaIds) {

        if (deptIds.length <= 0)
            return 0;
        Date now = new Date();
        JingfeiPici jingfeiPici = jingfeiPiciMapper.selectJingfeiPiciById(jingfeipiciId);//经费批次
        if (jingfeiPici.getIsjisuan().equals("0"))
            return 2;
        String deptId = jingfeiPici.getDeptid();

        final double zongjine = jingfeiPici.getZongjine();
        final double fafangjine = jingfeiPici.getFafangjine();

        //查询所选下级单位本批次单位的jingfeidept
        List<JingfeiDept> childJingfeiDeptList = jingfeiDeptMapper.selectAllByDeptIdsAndJingfeipiciId(deptIds, jingfeipiciId);
        List<JingfeiDetail> childJingfeiDetailList = jingfeiDetailMapper.selectAllByJingfeipiciidAndZhuangjiaids(jingfeipiciId, zhuanjiaIds);

        double trueFafangjine = 0.0;//本次实际发放金额
        for (JingfeiDept childJingfeiDept : childJingfeiDeptList) {
            String childDeptId = childJingfeiDept.getDeptid();
            JingfeiYue childJingfeiYue = jingfeiYueMapper.selectJingfeiYueByDeptid(childDeptId);
            if (childJingfeiYue == null) {
                childJingfeiYue = new JingfeiYue();
                childJingfeiYue.setDeptid(childDeptId);
                childJingfeiYue.setYue(0.0);
                childJingfeiYue.setZhiliu(0.0);
                childJingfeiYue.setDaifa(0.0);
                childJingfeiYue.setIsvalid(1);
                childJingfeiYue.setWeishoukuanyue(0.0);
                childJingfeiYue.setGengxinshijian(now);
                if (jingfeiYueMapper.insertJingfeiYue(childJingfeiYue) != 1) {
                    throw new RuntimeException("新建余额错误" + childDeptId);
                }
            }
            double childDeptZongjine = childJingfeiDept.getFafangjine();
            trueFafangjine += childDeptZongjine;
            childJingfeiYue.setWeishoukuanyue(childJingfeiYue.getWeishoukuanyue() + childDeptZongjine);
            childJingfeiDept.setIsfafang(1);
            if (jingfeiYueMapper.updateJingfeiYue(childJingfeiYue) != 1) {
                throw new RuntimeException("更新余额错误" + childDeptId);
            }
            if (jingfeiDeptMapper.updateJingfeiDept(childJingfeiDept) != 1)
                throw new RuntimeException("单位发放状态修改错误" + childDeptId);
        }
        for (JingfeiDetail jingfeiDetail : childJingfeiDetailList) {
            trueFafangjine += jingfeiDetail.getShifajine();
            jingfeiDetail.setIsshoudao(1);
            if (jingfeiDetailMapper.updateJingfeiDetail(jingfeiDetail) != 1)
                throw new RuntimeException("专家发放错误");
        }

        if (!deptId.equals("0")) {//专家中心没有余额，过滤掉
            JingfeiYue jingfeiYue = jingfeiYueMapper.selectJingfeiYueByDeptid(deptId);//本单位余额
            jingfeiYue.setYue(jingfeiYue.getYue() - trueFafangjine);//发放后余额 = 发放前余额 - 实际发放金额
            jingfeiYue.setDaifa(jingfeiYue.getDaifa()  - trueFafangjine);//待发 = 计划发放 - 实际发放
//            jingfeiYue.setZhiliu(jingfeiYue.getZhiliu() + zongjine - fafangjine);//滞留金额 = 发放前滞留金额 + 本批次总金额 - 计划发放金额
            if (jingfeiYueMapper.updateJingfeiYue(jingfeiYue) != 1)
                throw new RuntimeException("更新余额错误" + deptId);
        }
        List<JingfeiDept> allChildJingfeiDept = jingfeiDeptMapper.selectAllByJingfeipiciid(jingfeipiciId, 0);
        if (allChildJingfeiDept.size() > 0)
            jingfeiPici.setIsfafang(2);
        else
            jingfeiPici.setIsdangqianpici(0);
            jingfeiPici.setIsfafang(1);//是否发放字段

        jingfeiPici.setFafangshijian(now);
        if (jingfeiPiciMapper.updateJingfeiPici(jingfeiPici) != 1) {
            throw new RuntimeException("更新发放时间错误" + jingfeipiciId);
        }
        return 1;
    }

    /**
     * 确认收款
     *
     * @param jingfeipiciId 经费批次ID
     * @param deptId        单位ID
     * @return
     */
    @Override
    public int updateIsshoudaoByJingfeipiciidAndDeptid(String jingfeipiciId, String deptId) {
        int ok = 1;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        JingfeiDept jingfeiDept = jingfeiDeptMapper.selectJingfeiDeptByJingfeipiciIdAndDeptId(jingfeipiciId, deptId);
        JingfeiYue jingfeiYue = jingfeiYueMapper.selectJingfeiYueByDeptid(deptId);
        jingfeiYue.setYue(jingfeiYue.getYue() + jingfeiYue.getWeishoukuanyue());
        jingfeiYue.setDaifa(jingfeiYue.getDaifa() + jingfeiYue.getWeishoukuanyue());
        jingfeiYue.setWeishoukuanyue(0.0);

        //上级单位未发放
        if (jingfeiDept.getIsfafang() == 0) {
            return 2;
        }
        if (jingfeiYueMapper.updateJingfeiYue(jingfeiYue) != 1)
            throw new RuntimeException("更新余额错误" + jingfeiYue.getDeptid());
        jingfeiDept.setIsshoudao(1);
        jingfeiDept.setShoukuanshijian(new Date());
        if (jingfeiDeptMapper.updateJingfeiDept(jingfeiDept) != 1) {
            throw new RuntimeException("update jingfeiDept error" + jingfeiDept.getId());
        }
        return ok;
    }
//    /**
//     * 发放
//     *
//     * @param jingfeipiciId 经费批次ID
//     * @param deptId        单位ID
//     * @return
//     */
//    @Override
//    @Transactional
//    public int updateIsfafangByJingfeipiciidAndDeptid(String jingfeipiciId, String deptId) {
//        int isOk = 1;
//        ZoneId zoneId = ZoneId.systemDefault();
//        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
//        JingfeiPici jingfeiPici = jingfeiPiciMapper.selectJingfeiPiciById(jingfeipiciId);
//        JingfeiDept jingfeiDept = jingfeiDeptMapper.selectJingfeiDeptByJingfeipiciIdAndDeptId(jingfeipiciId, deptId);
//        if (jingfeiDept.getBeizhu4() == "0")
//            return 2;
//        jingfeiDept.setIsfafang(1);
//        LocalDateTime now = LocalDateTime.now();
//        String nowString = now.format(dateTimeFormatter);
//        jingfeiDept.setBeizhu2(nowString);
//        Dept parentDept = new Dept();
//        parentDept.setParentid(deptidOlddeptidService.DeptIdToOldDeptId(deptId));
//        List<Dept> childDeptList = deptMapper.selectDeptList(parentDept);
//        for (Dept dept : childDeptList) {
//            List<ZhuanjiaBiandongDetail> deptZhuanjiaBiandongDetailList = zhuanjiaBiandongDetailMapper
//                    .selectZhuanjiaBiandongDetailListByZhuanjiaIdAndDeptIdAndUsedAndTongguoOrJieshuTime(null,
//                            deptidOlddeptidService.OldDeptIdToDeptId(dept.getId()), "0", "1",
//                            jingfeiPici.getJisuanshijian().toInstant().atZone(zoneId).toLocalDateTime().format(dateTimeFormatter),
//                            jingfeiPici.getJieshunianyue().toInstant().atZone(zoneId).toLocalDateTime().format(dateTimeFormatter));
//            int notFafangCount = jingfeiDeptMapper.selectNotFafangCountByDeptId(deptidOlddeptidService.OldDeptIdToDeptId(dept.getId()));
//            if (jingfeiPici.getDeptid() == "0" || deptZhuanjiaBiandongDetailList != null
//                    && deptZhuanjiaBiandongDetailList.size() != 0 && notFafangCount <= 1) {
//
//            }
//            JingfeiDept childJingfeiDept = jingfeiDeptMapper.selectJingfeiDeptByJingfeipiciIdAndDeptId(jingfeipiciId,
//                    deptidOlddeptidService.OldDeptIdToDeptId(dept.getId()));
//            childJingfeiDept.setBeizhu1("1");
//            childJingfeiDept.setBeizhu5(nowString);
//            if (jingfeiDeptMapper.updateJingfeiDept(childJingfeiDept) != 1) {
//                isOk = 0;
//                throw new RuntimeException("update jingfeiDept error:" + dept.getId());
//            }
//        }
//        if (jingfeiDeptMapper.updateJingfeiDept(jingfeiDept) != 1) {
//            isOk = 0;
//            throw new RuntimeException("update jingfeiDept error:" + deptId);
//        }
//        return isOk;
//    }

    /**
     * 计算单位应发津贴
     *
     * @param jingfeiPici 当前经费批次
     * @return
     */
    @Override
    @Transactional
    public int jisuandanweijingfei(JingfeiPici jingfeiPici) {
        ZoneId zoneId = ZoneId.systemDefault();
        int ok = 1;
        String deptId = jingfeiPici.getDeptid();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        JingfeiPici finalJingfeiPici = jingfeiPiciMapper.selectJingfeiPiciById(jingfeiPici.getId());
        LocalDateTime jisuanshijian = finalJingfeiPici.getJisuanshijian().toInstant().atZone(zoneId).toLocalDateTime();
        LocalDateTime kaishishijian = finalJingfeiPici.getKaishinianyue().toInstant().atZone(zoneId).toLocalDateTime();
        LocalDateTime jieshushijian = finalJingfeiPici.getJieshunianyue().toInstant().atZone(zoneId).toLocalDateTime();
        LocalDateTime jiezhiLocalTime;
        String jiezhiTime;
        //如果计算时间在截至日期之前，则专家状态变动截至到计算时间；如果在截止日期之后，则专家状态变动截至到截止时间
//        if (jisuanshijian.isBefore(jieshushijian))
//            jiezhiLocalTime = jisuanshijian;
//        else
//            jiezhiLocalTime = jieshushijian;
        jiezhiTime = jisuanshijian.format(dateTimeFormatter);
        //查询上级单位是否给该单位发放了津贴
        int faCount = jingfeiDeptMapper.selectCountByDeptIdAndBetweenBeizhu1AndBeizhu2(
                deptId, dateTimeFormatter.format(kaishishijian), dateTimeFormatter.format(jieshushijian));
        List<ZhuanjiaBiandongDetail> deptZhuanjiaBiandongDetailList = zhuanjiaBiandongDetailMapper
                .selectZhuanjiaBiandongDetailListByZhuanjiaIdAndDeptIdAndUsedAndTongguoOrJieshuTime(null,
                        deptId, "0", "1",
                        jiezhiTime, jieshushijian.format(dateTimeFormatter));
//        int notFafangCount = jingfeiDeptMapper.selectNotFafangCountByDeptId(jingfeiPici.getDeptid());
        Dept parentDept = new Dept();
        parentDept.setParentid(deptidOlddeptidService.DeptIdToOldDeptId(deptId));
        List<Dept> childDeptList = deptMapper.selectDeptList(parentDept);

        double deptMoney = 0.0;//本单位的发放津贴总额
        double deptBufa = 0.0;
        int fafangrenshu = 0;//本单位发放人数
        int tingfarenshu = 0;//本单位停发人数
        int bufarenshu = 0;
        if (jingfeiPici.getBeizhu4() == "0")
            return 2;

        RenshuAndMoney renshuAndMoney = new RenshuAndMoney();
        //单位是否提交了专家状态

//        System.out.println("-------------------单位名称：" + deptMapper.selectDeptById(jingfeiPici.getDeptid()).getJigoumingcheng());
        if (jingfeiPici.getDeptid() == "0" || deptZhuanjiaBiandongDetailList != null
                && deptZhuanjiaBiandongDetailList.size() != 0 && faCount > 0) {// && notFafangCount <= 1
            //计算当前循环单位的专家的津贴和人数和下级单位列表
            renshuAndMoney = getRenshuAndMoney(deptidOlddeptidService.DeptIdToOldDeptId(deptId),
                    jingfeiPici.getId(), deptId, 1);
        } else {
            renshuAndMoney = getRenshuAndMoney(deptidOlddeptidService.DeptIdToOldDeptId(deptId),
                    jingfeiPici.getId(), deptId, 0);
        }
        deptMoney += renshuAndMoney.money;//本单位所属专家津贴总额
        tingfarenshu += renshuAndMoney.tingfarenshu;//本单位所属专家停发人数
        fafangrenshu += renshuAndMoney.fafangrenshu;//本单位所属专家发放人数

        //计算下级单位应发津贴金额
        for (Dept dept : childDeptList) {
            String newDeptId = deptidOlddeptidService.OldDeptIdToDeptId(dept.getId());
            List<ZhuanjiaBiandongDetail> deptZhuanjiaBiandongDetailList1 = zhuanjiaBiandongDetailMapper
                    .selectZhuanjiaBiandongDetailListByZhuanjiaIdAndDeptIdAndUsedAndTongguoOrJieshuTime(null,
                            deptidOlddeptidService.OldDeptIdToDeptId(dept.getId()), "0", "1",
                            jiezhiTime, jieshushijian.format(dateTimeFormatter));
//            int notFafangCount1 = jingfeiDeptMapper.selectNotFafangCountByDeptId(deptidOlddeptidService.OldDeptIdToDeptId(dept.getId()));
            int faCount1 = jingfeiDeptMapper.selectCountByDeptIdAndBetweenBeizhu1AndBeizhu2(
                    newDeptId, dateTimeFormatter.format(kaishishijian), dateTimeFormatter.format(jieshushijian));
            double deptMoney1 = 0.0;
            double deptBufa1 = 0.0;
            int fafangrenshu1 = 0;
            int tingfarenshu1 = 0;
            int bufarenshu1 = 0;

            parentDept.setParentid(dept.getId());
            List<Dept> childDeptList1 = deptMapper.selectDeptList(parentDept);
            for (Dept dept1 : childDeptList1) {
                //用于判断单位有无专家状态变动
                String newDept1Id = deptidOlddeptidService.OldDeptIdToDeptId(dept1.getId());
                List<ZhuanjiaBiandongDetail> deptZhuanjiaBiandongDetailList2 = zhuanjiaBiandongDetailMapper
                        .selectZhuanjiaBiandongDetailListByZhuanjiaIdAndDeptIdAndUsedAndTongguoOrJieshuTime(null,
                                newDept1Id, "0", "1",
                                jiezhiTime,
                                jieshushijian.format(dateTimeFormatter));
//                int notFafangCount2 = jingfeiDeptMapper.selectNotFafangCountByDeptId(deptidOlddeptidService.OldDeptIdToDeptId(dept1.getId()));
                //判断上上级单位有没有给本级发津贴，>0 就是发了
                int faCount2 = jingfeiDeptMapper.selectCountByDeptIdAndBetweenBeizhu1AndBeizhu2(
                        newDept1Id, dateTimeFormatter.format(kaishishijian), dateTimeFormatter.format(jieshushijian));
                //初始化本级单位数据
                double deptMoney2 = 0.0;
                double deptBufa2 = 0.0;
                int fafangrenshu2 = 0;
                int tingfarenshu2 = 0;
                int bufarenshu2 = 0;
                //下级单位列表
                parentDept.setParentid(dept1.getId());
                List<Dept> childDeptList2 = deptMapper.selectDeptList(parentDept);
                for (Dept dept2 : childDeptList2) {
                    String newDept2Id = deptidOlddeptidService.OldDeptIdToDeptId(dept2.getId());
                    //用于判断单位有无专家状态变动
                    List<ZhuanjiaBiandongDetail> deptZhuanjiaBiandongDetailList3 = zhuanjiaBiandongDetailMapper
                            .selectZhuanjiaBiandongDetailListByZhuanjiaIdAndDeptIdAndUsedAndTongguoOrJieshuTime(null,
                                    newDept2Id, "0", "1",
                                    jiezhiTime, jieshushijian.format(dateTimeFormatter));
//                    int notFafangCount3 = jingfeiDeptMapper.selectNotFafangCountByDeptId(deptidOlddeptidService.OldDeptIdToDeptId(dept2.getId()));
                    //判断上上级单位有没有给本级发津贴，>0 就是发了
                    int faCount3 = jingfeiDeptMapper.selectCountByDeptIdAndBetweenBeizhu1AndBeizhu2(
                            newDept2Id, dateTimeFormatter.format(kaishishijian), dateTimeFormatter.format(jieshushijian));
                    //初始化本级单位数据
                    double deptMoney3 = 0.0;
                    double deptBufa3 = 0.0;
                    int fafangrenshu3 = 0;
                    int tingfarenshu3 = 0;
                    int bufarenshu3 = 0;
                    parentDept.setParentid(dept2.getId());
                    List<Dept> childDeptList3 = deptMapper.selectDeptList(parentDept);
                    for (Dept dept3 : childDeptList3) {
                        String newDept3Id = deptidOlddeptidService.OldDeptIdToDeptId(dept3.getId());
                        List<ZhuanjiaBiandongDetail> deptZhuanjiaBiandongDetailList4 = zhuanjiaBiandongDetailMapper
                                .selectZhuanjiaBiandongDetailListByZhuanjiaIdAndDeptIdAndUsedAndTongguoOrJieshuTime(null,
                                        newDept3Id, "0", "1",
                                        jiezhiTime, jieshushijian.format(dateTimeFormatter));
//                        int notFafangCount4 = jingfeiDeptMapper.selectNotFafangCountByDeptId(deptidOlddeptidService.OldDeptIdToDeptId(dept3.getId()));
                        int faCount4 = jingfeiDeptMapper.selectCountByDeptIdAndBetweenBeizhu1AndBeizhu2(
                                newDept3Id, dateTimeFormatter.format(kaishishijian), dateTimeFormatter.format(jieshushijian));
                        if (deptZhuanjiaBiandongDetailList4 != null && deptZhuanjiaBiandongDetailList4.size() != 0
                                && (deptId.equals("0") || faCount4 > 0)) {//&& notFafangCount4 <= 1
                            renshuAndMoney = getRenshuAndMoney(dept3.getId(), jingfeiPici.getId(),
                                    jingfeiPici.getDeptid(), 1);
                            JingfeiDept jingfeiDept = jingfeiDeptMapper.selectAllByDeptIdAndJingfeipiciId(newDept3Id, jingfeiPici.getId());
                            if (jingfeiDept == null) {
                                jingfeiDept = new JingfeiDept();
                                jingfeiDept.setId(UUID.randomUUID().toString());
                                jingfeiDept.setDeptid(newDept3Id);
                                jingfeiDept.setJingfeipiciid(jingfeiPici.getId());
                                jingfeiDept.setJingfeipicimingcheng(finalJingfeiPici.getJingfeipicimingcheng());
                                jingfeiDept.setIsshoudao(0);
                                jingfeiDept.setIsvalid(1);
                                jingfeiDept.setIsfafang(0);
                                jingfeiDept.setBeizhu1(dateTimeFormatter.format(kaishishijian));
                                jingfeiDept.setBeizhu2(dateTimeFormatter.format(jieshushijian));
                                jingfeiDept.setFafangrenshu(renshuAndMoney.fafangrenshu);
                                jingfeiDept.setQuanerenshu(renshuAndMoney.fafangrenshu - renshuAndMoney.tingfarenshu - renshuAndMoney.bufarenshu);
                                jingfeiDept.setTingfarenshu(renshuAndMoney.tingfarenshu);
                                jingfeiDept.setFafangjine(renshuAndMoney.money);
                                jingfeiDept.setBeizhu3(String.valueOf(renshuAndMoney.bufaMoney));
                                if (jingfeiDeptMapper.insertJingfeiDept(jingfeiDept) != 1) {
                                    throw new RuntimeException("insert dept: " + jingfeiPici.getDeptid() + "error");
                                }
                            } else {
                                jingfeiDept.setBeizhu1(dateTimeFormatter.format(kaishishijian));
                                jingfeiDept.setBeizhu2(dateTimeFormatter.format(jieshushijian));
                                jingfeiDept.setIsfafang(0);
                                jingfeiDept.setJingfeipiciid(jingfeiPici.getId());
                                jingfeiDept.setJingfeipicimingcheng(finalJingfeiPici.getJingfeipicimingcheng());
                                jingfeiDept.setFafangrenshu(renshuAndMoney.fafangrenshu);
                                jingfeiDept.setQuanerenshu(renshuAndMoney.fafangrenshu - renshuAndMoney.tingfarenshu - renshuAndMoney.bufarenshu);
                                jingfeiDept.setTingfarenshu(renshuAndMoney.tingfarenshu);
                                jingfeiDept.setFafangjine(renshuAndMoney.money);
                                jingfeiDept.setBeizhu3(String.valueOf(renshuAndMoney.bufaMoney));

                                if (jingfeiDeptMapper.updateJingfeiDept(jingfeiDept) != 1)
                                    throw new RuntimeException("insert dept: " + jingfeiPici.getDeptid() + "error");
                            }
                        } else {
                            renshuAndMoney = getRenshuAndMoney(dept3.getId(), jingfeiPici.getId(),
                                    jingfeiPici.getDeptid(), 0);
                        }
                        //将数据加到上级单位
                        deptMoney3 += renshuAndMoney.money;
                        deptBufa3 += renshuAndMoney.bufaMoney;
                        tingfarenshu3 += renshuAndMoney.tingfarenshu;
                        fafangrenshu3 += renshuAndMoney.fafangrenshu;
                        bufarenshu3 += renshuAndMoney.bufarenshu;
                    }
                    if (deptZhuanjiaBiandongDetailList3 != null && deptZhuanjiaBiandongDetailList3.size() != 0
                            && (deptId.equals("0") || faCount3 > 0)) {//&& notFafangCount3 <= 1
                        renshuAndMoney = getRenshuAndMoney(dept2.getId(), jingfeiPici.getId(),
                                jingfeiPici.getDeptid(), 1);
                        deptMoney3 += renshuAndMoney.money;
                        deptBufa3 += renshuAndMoney.bufaMoney;
                        tingfarenshu3 += renshuAndMoney.tingfarenshu;
                        fafangrenshu3 += renshuAndMoney.fafangrenshu;
                        JingfeiDept jingfeiDept = jingfeiDeptMapper.selectAllByDeptIdAndJingfeipiciId(newDept2Id, jingfeiPici.getId());
                        if (jingfeiDept == null) {
                            jingfeiDept = new JingfeiDept();
                            jingfeiDept.setId(UUID.randomUUID().toString());
                            jingfeiDept.setDeptid(newDept2Id);
                            jingfeiDept.setJingfeipiciid(jingfeiPici.getId());
                            jingfeiDept.setJingfeipicimingcheng(finalJingfeiPici.getJingfeipicimingcheng());
                            jingfeiDept.setIsshoudao(0);
                            jingfeiDept.setIsvalid(1);
                            jingfeiDept.setIsfafang(0);
                            jingfeiDept.setBeizhu1(dateTimeFormatter.format(kaishishijian));
                            jingfeiDept.setBeizhu2(dateTimeFormatter.format(jieshushijian));
                            jingfeiDept.setFafangrenshu(fafangrenshu3);
                            jingfeiDept.setQuanerenshu(fafangrenshu3 - tingfarenshu3 - bufarenshu3);
                            jingfeiDept.setTingfarenshu(tingfarenshu3);
                            jingfeiDept.setFafangjine(deptMoney3);
                            if (jingfeiDeptMapper.insertJingfeiDept(jingfeiDept) != 1) {
                                throw new RuntimeException("insert dept: " + jingfeiPici.getDeptid() + "error");
                            }
                        } else {
                            jingfeiDept.setBeizhu1(dateTimeFormatter.format(kaishishijian));
                            jingfeiDept.setBeizhu2(dateTimeFormatter.format(jieshushijian));
                            jingfeiDept.setIsfafang(0);
                            jingfeiDept.setJingfeipiciid(jingfeiPici.getId());
                            jingfeiDept.setJingfeipicimingcheng(finalJingfeiPici.getJingfeipicimingcheng());
                            jingfeiDept.setFafangrenshu(fafangrenshu3);
                            jingfeiDept.setQuanerenshu(fafangrenshu3 - tingfarenshu3 - bufarenshu3);
                            jingfeiDept.setTingfarenshu(tingfarenshu3);
                            jingfeiDept.setFafangjine(deptMoney3);

                            if (jingfeiDeptMapper.updateJingfeiDept(jingfeiDept) != 1)
                                throw new RuntimeException("insert dept: " + jingfeiPici.getDeptid() + "error");
                        }
                    } else {
                        renshuAndMoney = getRenshuAndMoney(dept2.getId(), jingfeiPici.getId(),
                                jingfeiPici.getDeptid(), 0);
                        deptMoney3 += renshuAndMoney.money;
                        deptBufa3 += renshuAndMoney.bufaMoney;
                        tingfarenshu3 += renshuAndMoney.tingfarenshu;
                        fafangrenshu3 += renshuAndMoney.fafangrenshu;
                    }

                    //将数据加到上级单位
                    deptMoney2 += deptMoney3;
                    deptBufa2 += deptBufa3;
                    fafangrenshu2 += fafangrenshu3;
                    tingfarenshu2 += tingfarenshu3;
                    bufarenshu2 += bufarenshu3;

//
                }
                if (deptZhuanjiaBiandongDetailList2 != null && deptZhuanjiaBiandongDetailList2.size() != 0
                        && (deptId.equals("0") || faCount2 > 0)) {//&& notFafangCount2 <= 1
                    //计算当前循环单位的专家的津贴和人数和下级单位列表
                    renshuAndMoney = getRenshuAndMoney(dept1.getId(), jingfeiPici.getId(),
                            jingfeiPici.getDeptid(), 1);
                    deptMoney2 += renshuAndMoney.money;
                    deptBufa2 += renshuAndMoney.bufaMoney;
                    tingfarenshu2 += renshuAndMoney.tingfarenshu;
                    fafangrenshu2 += renshuAndMoney.fafangrenshu;
                    bufarenshu2 += renshuAndMoney.bufarenshu;
                    JingfeiDept jingfeiDept = jingfeiDeptMapper.selectAllByDeptIdAndJingfeipiciId(newDept1Id, jingfeiPici.getId());
                    if (jingfeiDept == null) {
                        jingfeiDept = new JingfeiDept();
                        jingfeiDept.setId(UUID.randomUUID().toString());
                        jingfeiDept.setDeptid(newDept1Id);
                        jingfeiDept.setJingfeipiciid(jingfeiPici.getId());
                        jingfeiDept.setJingfeipicimingcheng(finalJingfeiPici.getJingfeipicimingcheng());
                        jingfeiDept.setIsshoudao(0);
                        jingfeiDept.setIsvalid(1);
                        jingfeiDept.setIsfafang(0);
                        jingfeiDept.setBeizhu1(dateTimeFormatter.format(kaishishijian));
                        jingfeiDept.setBeizhu2(dateTimeFormatter.format(jieshushijian));
                        jingfeiDept.setFafangrenshu(fafangrenshu2);
                        jingfeiDept.setQuanerenshu(fafangrenshu2 - tingfarenshu2 - bufarenshu2);
                        jingfeiDept.setTingfarenshu(tingfarenshu2);
                        jingfeiDept.setFafangjine(deptMoney2);
                        jingfeiDept.setBeizhu3(String.valueOf(deptBufa2));
                        if (jingfeiDeptMapper.insertJingfeiDept(jingfeiDept) != 1) {
                            throw new RuntimeException("insert dept: " + jingfeiPici.getDeptid() + "error");
                        }
                    } else {
                        jingfeiDept.setBeizhu1(dateTimeFormatter.format(kaishishijian));
                        jingfeiDept.setBeizhu2(dateTimeFormatter.format(jieshushijian));
                        jingfeiDept.setIsfafang(0);
                        jingfeiDept.setJingfeipiciid(jingfeiPici.getId());
                        jingfeiDept.setJingfeipicimingcheng(finalJingfeiPici.getJingfeipicimingcheng());
                        jingfeiDept.setFafangrenshu(fafangrenshu2);
                        jingfeiDept.setQuanerenshu(fafangrenshu2 - tingfarenshu2 - bufarenshu2);
                        jingfeiDept.setTingfarenshu(tingfarenshu2);
                        jingfeiDept.setFafangjine(deptMoney2);
                        jingfeiDept.setBeizhu3(String.valueOf(deptBufa2));
                        if (jingfeiDeptMapper.updateJingfeiDept(jingfeiDept) != 1)
                            throw new RuntimeException("insert dept: " + jingfeiPici.getDeptid() + "error");
                    }
                } else {
                    renshuAndMoney = getRenshuAndMoney(dept1.getId(), jingfeiPici.getId(),
                            jingfeiPici.getDeptid(), 0);
                    deptMoney2 += renshuAndMoney.money;
                    deptBufa2 += renshuAndMoney.bufaMoney;
                    tingfarenshu2 += renshuAndMoney.tingfarenshu;
                    fafangrenshu2 += renshuAndMoney.fafangrenshu;
                    bufarenshu2 += renshuAndMoney.bufarenshu;
                }
                //将数据加到上级单位
                deptMoney1 += deptMoney2;
                deptBufa1 += deptBufa2;
                fafangrenshu1 += fafangrenshu2;
                tingfarenshu1 += tingfarenshu2;
                bufarenshu1 += bufarenshu2;
            }

            if (deptZhuanjiaBiandongDetailList1 != null && deptZhuanjiaBiandongDetailList1.size() != 0
                    && (deptId.equals("0") || faCount1 > 0)) {//&& notFafangCount1 <= 1
                renshuAndMoney = getRenshuAndMoney(dept.getId(), jingfeiPici.getId(),
                        jingfeiPici.getDeptid(), 1);
            } else {
                renshuAndMoney = getRenshuAndMoney(dept.getId(), jingfeiPici.getId(),
                        jingfeiPici.getDeptid(), 0);
            }
            deptMoney1 += renshuAndMoney.money;
            deptBufa1 +=renshuAndMoney.bufaMoney;
            tingfarenshu1 += renshuAndMoney.tingfarenshu;
            fafangrenshu1 += renshuAndMoney.fafangrenshu;
            bufarenshu1 += renshuAndMoney.bufarenshu;
            JingfeiDept jingfeiDept = jingfeiDeptMapper.selectAllByDeptIdAndJingfeipiciId(newDeptId, jingfeiPici.getId());
            if (jingfeiDept == null) {
                jingfeiDept = new JingfeiDept();
                jingfeiDept.setId(UUID.randomUUID().toString());
                jingfeiDept.setDeptid(newDeptId);
                jingfeiDept.setJingfeipiciid(jingfeiPici.getId());
                jingfeiDept.setJingfeipicimingcheng(finalJingfeiPici.getJingfeipicimingcheng());
                jingfeiDept.setIsshoudao(0);
                jingfeiDept.setIsvalid(1);
                jingfeiDept.setIsfafang(0);
                jingfeiDept.setBeizhu1(dateTimeFormatter.format(kaishishijian));
                jingfeiDept.setBeizhu2(dateTimeFormatter.format(jieshushijian));
                jingfeiDept.setFafangrenshu(fafangrenshu1);
                jingfeiDept.setQuanerenshu(fafangrenshu1 - tingfarenshu1 - bufarenshu1);
                jingfeiDept.setTingfarenshu(tingfarenshu1);
                jingfeiDept.setFafangjine(deptMoney1);
                jingfeiDept.setBeizhu3(String.valueOf(deptBufa1));
                if (jingfeiDeptMapper.insertJingfeiDept(jingfeiDept) != 1) {
                    throw new RuntimeException("insert dept: " + jingfeiPici.getDeptid() + "error");
                }
            } else {
                jingfeiDept.setBeizhu1(dateTimeFormatter.format(kaishishijian));
                jingfeiDept.setBeizhu2(dateTimeFormatter.format(jieshushijian));
                jingfeiDept.setIsfafang(0);
                jingfeiDept.setJingfeipiciid(jingfeiPici.getId());
                jingfeiDept.setJingfeipicimingcheng(finalJingfeiPici.getJingfeipicimingcheng());
                jingfeiDept.setFafangrenshu(fafangrenshu1);
                jingfeiDept.setQuanerenshu(fafangrenshu1 - tingfarenshu1 - bufarenshu1);
                jingfeiDept.setTingfarenshu(tingfarenshu1);
                jingfeiDept.setFafangjine(deptMoney1);
                jingfeiDept.setBeizhu3(String.valueOf(deptBufa1));

                if (jingfeiDeptMapper.updateJingfeiDept(jingfeiDept) != 1)
                    throw new RuntimeException("insert dept: " + jingfeiPici.getDeptid() + "error");
            }
            //将数据加到上级单位
            deptMoney += deptMoney1;//加上所有下级单位津贴总额
            deptBufa += deptBufa1;
            fafangrenshu += fafangrenshu1;//加上所有下级单位发放人数
            tingfarenshu += tingfarenshu1;//加上所有下级单位停发人数
            bufarenshu += bufarenshu1;
        }

//        List<DeptZhuanjia> deptZhuanjiaList = deptZhuanjiaMapper.selectAllByDeptIdAndIsvalid(jingfeiPici.getDeptid());
//        for (DeptZhuanjia deptZhuanjia : deptZhuanjiaList) {
//            deptZhuanjia.setIsvalid(0L);
//            if (deptZhuanjiaMapper.updateDeptZhuanjia(deptZhuanjia) != 1) {
//                throw new RuntimeException("update deptZhuanjia error" + deptZhuanjia.getXingming());
//            }
//        }

        finalJingfeiPici.setFafangjine(deptMoney);
        finalJingfeiPici.setTingfarenshu(tingfarenshu);
        finalJingfeiPici.setFafanrenshu(fafangrenshu);
        finalJingfeiPici.setQuanerenshu(fafangrenshu - tingfarenshu);
        finalJingfeiPici.setIsjisuan("1");

        if (finalJingfeiPici.getZongjine() == null)
            finalJingfeiPici.setZongjine(0.0);
        finalJingfeiPici.setZongjine(deptMoney);
        if (jingfeiPiciMapper.updateJingfeiPici(finalJingfeiPici) != 1) {
            throw new RuntimeException("Update pici: " + jingfeiPici.getId() + "error");
        }

        List<ZhuanjiaBiandongDetail> zhuanjiaBiandongDetailList;
        //将专家变动数据变成已使用
        if (jisuanshijian.isBefore(jieshushijian)) {
            zhuanjiaBiandongDetailList = zhuanjiaBiandongDetailMapper.selectAllByDeptIdAndUsedAndTongguoOrJieshuTime(jingfeiPici.getDeptid(), "0", "1", jisuanshijian.format(dateTimeFormatter));
        } else {
            zhuanjiaBiandongDetailList = zhuanjiaBiandongDetailMapper.selectAllByDeptIdAndUsedAndTongguoOrJieshuTime(
                    jingfeiPici.getDeptid(), "0", "1", jieshushijian.format(dateTimeFormatter));
        }

        for (ZhuanjiaBiandongDetail zhuanjiaBiandongDetail : zhuanjiaBiandongDetailList) {
            if (tingfazhuangtaiList.contains(zhuanjiaBiandongDetail.getBiandongleixing())
                    || zhuanjiaBiandongDetail.getShenpishijian().before(Date.from(jisuanshijian.atZone(zoneId).toInstant()))) {
                zhuanjiaBiandongDetail.setIsused(1L);
                if (zhuanjiaBiandongDetailMapper.updateZhuanjiaBiandongDetail(zhuanjiaBiandongDetail) != 1)
                    throw new RuntimeException("update zhuanjiabiandongDetail error" + zhuanjiaBiandongDetail.getZhuanjiamingcheng());
            }
        }
        return ok;
    }

    /**
     * 计算单位下单个专家津贴
     *
     * @param deptId        old单位ID
     * @param jingfeipiciId 经费批次ID
     * @param nowDeptId     当前点批次计算的单位ID
     * @param isjisuan      单位是否提交了专家变动且单位是否发放了上批次津贴
     * @return
     */
    private RenshuAndMoney getRenshuAndMoney(String deptId, String jingfeipiciId, String nowDeptId, int isjisuan) {

        RenshuAndMoney renshuAndMoney = new RenshuAndMoney();
        List<Zhuanjia> zhuanjiaList = zhuanjiaMapper.selectZhuanjiaByDeptID(deptId,
                deptidOlddeptidService.OldDeptIdToDeptId(deptId));

        for (Zhuanjia zhuanjia : zhuanjiaList) {
            if (isjisuan == 1) {
                jingfeiDetailService.jisuanzhuanjiajintie(jingfeipiciId,
                        deptidOlddeptidService.OldDeptIdToDeptId(deptId), zhuanjia.getZhuanjiaid(), nowDeptId, isjisuan);
                JingfeiDetail jingfeiDetail = jingfeiDetailMapper
                        .selectAllByZhuangjiaidAndJingfeipiciIdAndDeptId(zhuanjia.getZhuanjiaid(),
                                deptidOlddeptidService.OldDeptIdToDeptId(deptId), jingfeipiciId);
                renshuAndMoney.money += jingfeiDetail.getShifajine();
                renshuAndMoney.bufaMoney += jingfeiDetail.getBufajine();
                if (jingfeiDetail.getIstingfa() == 1)
                    renshuAndMoney.tingfarenshu++;
                if (jingfeiDetail.getIsbufa() == 1)
                    renshuAndMoney.bufarenshu++;
                renshuAndMoney.fafangrenshu++;
            }
        }
        return renshuAndMoney;
    }



    private class RenshuAndMoney {

        private int tingfarenshu = 0;

        private int fafangrenshu = 0;

        private int bufarenshu = 0;

        private double money = 0.0;

        private double bufaMoney = 0.0;
    }
}
